package com.lyx.raindrop.ui;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hjq.toast.ToastUtils;
import com.lyx.framework.base.BaseUIActivity;
import com.lyx.framework.bmob.BmobManager;
import com.lyx.framework.bmob.UserEntity;
import com.lyx.framework.manager.KeyWordManager;
import com.lyx.framework.utils.CommonUtils;
import com.lyx.framework.utils.LogUtils;
import com.lyx.framework.utils.PhoneUtils;
import com.lyx.raindrop.R;
import com.lyx.raindrop.adapter.AddFriendAdapter;
import com.lyx.raindrop.model.AddFriendModel;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;

public class AddFriendActivity extends BaseUIActivity implements View.OnClickListener {

    //标题
    public static final int TYPE_TITLE = 0;
    //内容
    public static final int TYPE_CONTENT = 1;

    private String lastSearchPhone = "";

    /**
     * 1.模拟用户数据
     * 2.根据条件查询
     * 3.推荐好友
     */
    private LinearLayout ll_to_contact;
    private EditText et_phone;
    private ImageView iv_search;
    private RecyclerView mSearchResultView;

    private View include_empty_view;

    private AddFriendAdapter mAddFriendAdapter;
    private List<AddFriendModel> mList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_friend);
        initView();
    }

    //初始化View
    private void initView() {
        include_empty_view = findViewById(R.id.include_empty_view);
        ll_to_contact = findViewById(R.id.ll_to_contact);
        et_phone = findViewById(R.id.et_phone);
        iv_search = findViewById(R.id.iv_search);
        mSearchResultView = findViewById(R.id.mSearchResultView);
        ll_to_contact.setOnClickListener(this);
        iv_search.setOnClickListener(this);

        //列表的实现
        mSearchResultView.setLayoutManager(new LinearLayoutManager(this));
        mSearchResultView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));

        if (mAddFriendAdapter == null) {
            mAddFriendAdapter = new AddFriendAdapter(this, mList);
        }
        mAddFriendAdapter.setOnItemClickListener(new AddFriendAdapter.IOnItemClickListener() {
            @Override
            public void onItemClickListener(int position) {
                UserInfoActivity.startActivity(AddFriendActivity.this, mList.get(position).getUserId());
            }
        });
        mSearchResultView.setAdapter(mAddFriendAdapter);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            //跳转到从通讯录导入
            case R.id.ll_to_contact:
                //处理权限
                if (checkPermissions(Manifest.permission.READ_CONTACTS)) {
                    startActivity(new Intent(this, ContactFriendActivity.class));
                } else {
                    requestPermission(new String[]{Manifest.permission.READ_CONTACTS});
                }
                break;
            case R.id.iv_search:
                queryPhoneUser();
                break;
        }
    }

    //通过电话号码查询
    private void queryPhoneUser() {
        //1.获取电话号码
        final String phone = et_phone.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            ToastUtils.show(getString(R.string.text_login_phone_null));
            return;
        }
        if (phone.equals(lastSearchPhone)) {
            return;
        }
        if (PhoneUtils.isNotValidChinesePhone(phone)) {
            ToastUtils.show(getString(R.string.text_login_phone_valid));
            return;
        }
        //2.过滤自己
        String phoneNumber = BmobManager.getInstance().getUser().getMobilePhoneNumber();
        LogUtils.getInstance().i("phoneNumber:" + phoneNumber);
        if (phone.equals(phoneNumber)) {
            ToastUtils.show(getString(R.string.text_add_friend_no_me));
            return;
        }
        lastSearchPhone = phone;
        //3.查询
        BmobManager.getInstance().queryPhoneUser(phone, new FindListener<UserEntity>() {
            @Override
            public void done(List<UserEntity> list, BmobException e) {
                KeyWordManager.getInstance().hideKeyWord(AddFriendActivity.this);
                if (e != null) {
                    return;
                }
                if (CommonUtils.isEmpty(list)) {
                    UserEntity imUser = list.get(0);
                    include_empty_view.setVisibility(View.GONE);
                    mSearchResultView.setVisibility(View.VISIBLE);
                    //每次你查询有数据的话则清空
                    mList.clear();
                    addTitle(getString(R.string.text_add_friend_title));
                    addContent(imUser);
                    mAddFriendAdapter.notifyDataSetChanged();
                    //推荐
                    pushUser(phone);
                } else {
                    //显示空数据
                    include_empty_view.setVisibility(View.VISIBLE);
                    mSearchResultView.setVisibility(View.GONE);
                }
            }
        });
    }

    //推荐好友
    private void pushUser(final String phone) {
        //查询所有的好友 取100个
        BmobManager.getInstance().queryAllUser(new FindListener<UserEntity>() {
            @Override
            public void done(List<UserEntity> list, BmobException e) {
                if (e == null) {
                    if (CommonUtils.isEmpty(list)) {
                        addTitle(getString(R.string.text_add_friend_content));
                        int num = (list.size() <= 100) ? list.size() : 100;
                        String phoneNumber = BmobManager.getInstance().getUser().getMobilePhoneNumber();
                        for (int i = 0; i < num; i++) {
                            //也不能自己推荐给自己
                            if (list.get(i).getMobilePhoneNumber().equals(phoneNumber)) {
                                //跳过本次循环
                                continue;
                            }
                            //也不能查询到所查找的好友
                            if (list.get(i).getMobilePhoneNumber().equals(phone)) {
                                //跳过本次循环
                                continue;
                            }
                            addContent(list.get(i));
                        }
                        mAddFriendAdapter.notifyItemRangeChanged(2, mList.size());
                    }
                }
            }
        });
    }

    //添加头部
    private void addTitle(String title) {
        AddFriendModel model = new AddFriendModel();
        model.setType(TYPE_TITLE);
        model.setTitle(title);
        mList.add(model);
    }

    //添加内容
    private void addContent(UserEntity imUser) {
        AddFriendModel model = new AddFriendModel();
        model.setType(TYPE_CONTENT);
        model.setUserId(imUser.getObjectId());
        model.setPhoto(imUser.getPhoto());
        model.setSex(imUser.isSex());
        model.setAge(imUser.getAge());
        model.setNickName(imUser.getNickName());
        model.setDesc(imUser.getDesc());
        mList.add(model);
    }

}
